
#include "c-utils/utils.h"
#include "c-utils/utils_log.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
#include <sys/resource.h>
#include <ifaddrs.h>
#include <arpa/inet.h>

int _if_info()
{
    struct ifaddrs *ifAddrStruct = NULL, *ifa = NULL;
    getifaddrs(&ifAddrStruct);
    if (NULL == ifAddrStruct)
        return 0;
    int if_num = 0;
    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
    {
        utils_if_info info = utils_net_if_info(ifa->ifa_name);
        // log_debug("idx: %d, mac: %s, speed: %d,duplex: %d, ipv4 addr: %s", info.if_idx, info.if_mac, info.speed, info.duplex, info.ipv4.addr);
        if (strcmp(ifa->ifa_name, info.if_name) == 0)
            if_num++;
    }
    freeifaddrs(ifAddrStruct);
    return if_num;
}

int _if_info_by_ip()
{
    struct in_addr sin_addr = {0};
    const char *addr = "127.0.0.1";
    inet_pton(AF_INET, addr, &sin_addr);
    utils_if_info info = utils_net_if_info_by_local_ip(sin_addr.s_addr);
    // log_debug("idx: %d, mac: %s, speed: %d,ipv4 addr: %s", info.if_idx, info.if_mac, info.speed, info.ipv4.addr);
    if (strlen(info.if_name) > 0)
        return 1;
    return 0;
}

int _check_net()
{
    if (utils_net_available(NULL, 0, 0, 0))
        if (utils_net_available(NULL, 80, 1, 0))
            return 1;
    return 0;
}

int _start_if()
{
    if (_if_info() == 0)
        return -1;
    if (_if_info_by_ip() == 0)
        return -1;
    if (_check_net() == 0)
        return -1;
    return 0;
}

int test_net(int argc, const char *argv[])
{
    int ret = 0;
    if (argc == 2)
    {
        int loops = atoi(argv[1]);
        int i = 0;
        for (; i < loops; i++)
        {
            ret = _start_if();
            if (ret)
                break;
            if (i % 100 == 0)
            {
                struct rusage _usage;
                struct sysinfo _sysinfo = {0};
                getrusage(RUSAGE_SELF, &_usage);
                sysinfo(&_sysinfo);
                log_info("mem buff: %ld, rmem: %ld\n", _sysinfo.bufferram, _usage.ru_maxrss);
            }
        }
    }
    else
        ret = _start_if();

    return ret;
}